﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Web;

namespace TireService.Web.UserControls.StatusOverview
{
    public partial class ucServiceCarUtilizationOverview : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                TireServiceDB db = new TireServiceDB();

                // Show default start and end of present month
                txtStartDate.Value = "01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
                txtEndDate.Value = Convert.ToDateTime("01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString()).AddMonths(1).AddDays(-1).Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();

                // Bind dropdownlist Servicecar
                ddlServiceCar.DataSource = db.GetServiceCars();
                ddlServiceCar.ValueField = "ServiceCarId";
                ddlServiceCar.TextField = "Description";
                ddlServiceCar.DataBind();
                ddlServiceCar.SelectedIndex = 1;

                BindServiceCarUtilizationData(db, Convert.ToInt32(ddlServiceCar.SelectedItem.Value), Convert.ToDateTime(txtStartDate.Value), Convert.ToDateTime(txtEndDate.Value), Convert.ToInt32(ddlChartMethod.SelectedItem.Value));
            }
        }

        /// <summary>
        /// Bind chart data
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarId">Id on service car</param>
        /// <param name="Startdate">Startdate for data to show in chart</param>
        /// <param name="Enddate">Enddate for data to show in chart</param>
        /// <param name="ChartMethod">Chart method to use (StakedBar or Full-StackedBar</param>
        private void BindServiceCarUtilizationData(TireServiceDB db, int ServiceCarId, DateTime Startdate, DateTime Enddate, int ChartMethod)
        {
            // Steps

            // 1. Hent alle service vogne
            var details = from p in db.ServiceCarScheduleDetails
                          join v in db.ScheduleDetailTypes on p.ScheduleDetailTypeId equals v.ScheduleDetailTypeId into pv
                          from x in pv.DefaultIfEmpty()
                          join y in db.ServiceCars on p.ServiceCarId equals y.ServiceCarId into py
                          from z in py.DefaultIfEmpty()
                          where p.ScheduleDate >= Startdate & p.ScheduleDate <= Enddate & p.ServiceCarId == ServiceCarId
                          group p by new
                          {
                              ServiceCarDescription = z.Description,
                              p.ScheduleDate,
                              ScheduleDetailTypeDescription = x.Description
                          }
                              into grp
                              select new
                              {
                                  grp.Key.ServiceCarDescription,
                                  grp.Key.ScheduleDate,
                                  grp.Key.ScheduleDetailTypeDescription,
                                  ScheduleDetailTypeCount = grp.Count()
                              };

            chartServiceCarUtilization.SeriesDataMember = "ScheduleDetailTypeDescription";
            chartServiceCarUtilization.SeriesTemplate.ArgumentDataMember = "ScheduleDate";
            chartServiceCarUtilization.SeriesTemplate.ArgumentScaleType = DevExpress.XtraCharts.ScaleType.DateTime;
            chartServiceCarUtilization.SeriesTemplate.ValueScaleType = DevExpress.XtraCharts.ScaleType.Numerical;
            chartServiceCarUtilization.SeriesTemplate.ValueDataMembers[0] = "ScheduleDetailTypeCount";
            
            chartServiceCarUtilization.DataSource = details;
            chartServiceCarUtilization.DataBind();

            foreach (Series serie in chartServiceCarUtilization.Series)
            {
                if (ChartMethod == 0)
                {
                    serie.ChangeView(ViewType.StackedBar);    
                }
                if (ChartMethod == 1)
                {
                    serie.ChangeView(ViewType.FullStackedBar);
                    ((FullStackedBarPointOptions)serie.PointOptions).PercentOptions.ValueAsPercent = true;
                    
                }
            }

            AxisLabel AxisLabel = ((XYDiagram)chartServiceCarUtilization.Diagram).AxisX.Label;
            AxisLabel.Angle = -90;
            //.ResolveOverlappingOptions.AllowHide = true;
            //AxisLabel.ResolveOverlappingOptions.AllowRotate = true;
            //AxisLabel.ResolveOverlappingOptions.AllowStagger = true;

            //foreach (var detail in details)
            //{
            //    // Create an empty Bar series and add it to the chart.
            //    Series series = new Series(servicecar.Description, ViewType.StackedBar);
            //    chartServiceCarUtilization.Series.Add(series);

            //    // Generate a data table and bind the series to it.
            //    series.DataSource = details.Where(p => p.ServiceCarDescription == servicecar.Description);

            //    // Specify data members to bind the series.
            //    series.ArgumentScaleType = ScaleType.DateTime;
            //    series.ArgumentDataMember = "ScheduleDate";
            //    series.ValueScaleType = ScaleType.Numerical;
            //    series.ValueDataMembers.AddRange(new string[] { "ScheduleDetailTypeDescription" });
            //}

            
            


            //List<ServiceCar> servicecars = db.GetServiceCars();

            //foreach (ServiceCar servicecar in servicecars)
            //{
                
            //}
        }

        /// <summary>
        /// Callback function that refreshes Chart
        /// </summary>
        protected void chartServiceCarUtilization_CustomCallback(object sender, CustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Get values (0: ServiceCarId, 1: Startdate, 2: Enddate, 3)
            string[] param = e.Parameter.Split('|');

            int ServiceCarId = Convert.ToInt32(param[0]);
            DateTime Startdate = Convert.ToDateTime(param[1]);
            DateTime Enddate = Convert.ToDateTime(param[2]);
            int ChartMethod = Convert.ToInt32(param[3]);

            BindServiceCarUtilizationData(db, ServiceCarId, Startdate, Enddate, ChartMethod);
        }
    }
}